﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using TA.JSON;

namespace TA.Turbo
{
	/// <summary>
	/// HTTP handler which outputs a small form which contains the INPUT tag with the type of FILE for the FileUpload control.
	/// </summary>
	public class FileUploadHandler : IHttpHandler
	{
		#region PUBLIC
		#region PROPS
		/// <summary>
		/// Gets true.
		/// </summary>
		public bool IsReusable
		{
			get { return true; }
		}
		#endregion
		#region METHODS
		/// <summary>
		/// Processes the request, either rendering the form or saving the submitted file to memory.
		/// </summary>
		/// <param name="context"></param>
		public void ProcessRequest(HttpContext context)
		{
			string id = context.Request.QueryString["i"];
			string token = context.Request.QueryString["t"];
			bool getStatus = context.Request.QueryString["s"] != null;
			if (getStatus)
			{
				this.ProcessRequest_Status(context, token);
			}
			else
			{
				this.ProcessRequest_Form(context, id, context.get_Operation());
			}
		}
		#endregion
		#endregion
		#region INTERNAL
		#region CONST/STATIC
		internal const string SessionKeyPrefix = "TA.Turbo.FileUpload*";
		static readonly Random _rnd = new Random();
		#endregion
		#region METHODS
		private void ProcessRequest_Form(HttpContext context, string id, FileUploadOperation oper)
		{
			context.Response.Write(string.Format(@"
<html>
	<body style=""margin:0;padding:0;"">
		<form method=""post"" enctype=""multipart/form-data"" style=""margin:0;padding:0;"">
		<input type=""submit"" id=""button"" name=""submit"" style=""display:none;"" />
		<input type=""file"" id=""file"" name=""file"" style=""width:205px;"" />
		<span id=""spanProgress"" style=""display:none;"">Uploading ...</span>
"));


			if (oper != null && oper.Files.Length > 0)
			{
				context.Response.Write(string.Format(@"
		<script type=""text/javascript"">
		parent.document.getElementById(""{0}"")[""_C""](""{1}"");
		</script>
", id, oper.Token));
			}


			context.Response.Write(@"
		</form>
	</body>
</html>
");
		}
		private void ProcessRequest_Status(HttpContext context, string token)
		{
			FileUploadOperation oper = FileUploadOperation.Get(context, token);
			if (oper == null)
				context.Response.Write("null");
			else
			{
				JsonWriter jw = new JsonWriter(context.Response.Output);
				FileUploadProgress progress = oper.Progress;
				progress.Serialize(jw);
			}
		}
		#endregion
		#endregion
	}
}
